<style>
    .add_product .txt{
        padding-bottom: 100px;
    }
    .add_product .pic_box{
        width: 100%;
        padding-bottom: 10px;
        color: #999999;
        display: flex;
        flex-wrap: wrap;
        background: #F5F6F7;
        justify-content: space-between;
    }
    .add_product  .pic_box .case_pic{
        margin-top: 10px;
        background: #fff;
        width:49%;
    }
    .add_product .pic_box .case_pic img{
        width:100%;
        height: 49vw;
        box-sizing: border-box;
    }
    .add_product .pic_box .case_pic p{
        margin: 15px auto;
        padding: 0 10px;
    }
    .add_product .diy_case_pic{
        width:100%;
        height: 100%;
        position: fixed;
        z-index: 999;
        background: #000;
    }
    .add_product .diy_case_pic .case_pic{
        width:100%;
        height: 100vw;
        position: absolute;
        right: 0;left: 0;top: 0;bottom: 0;
        margin: auto;
    }
    .add_product .switch{
        padding: 10px 15px;
    }
    .add_product .switch p{
        padding-top:8px;
        display: block;
        float: left;
        margin-right: 32px;
    }
    .add_product .switch p:nth-child(2){
        color: #999;
        padding: 8px 0 0 0;
        box-sizing: border-box;
    }
    .add_product .van-switch{
        float: right;
    }
    .add_product .bottom{
        clear: both;
        position: relative;
    }
    .add_product .fm_btn{
        margin-top: 15px;
        position: initial;
    }
   .add_product .upload_pro::after{
       content: none;
   }
   .van-uploader{
       display: block;
   }
    .add_product h3{
         padding: 10px 15px;
    }

    .add_product .van-field__control:disabled{
         color: #555;
     }
    .add_product .explain{
         border-bottom: 1px solid #eee;
         width:94%;
         margin: auto;
         padding:10px 0;
     }
     .upload_btn{
        width:80%;
        display: block;
        background: #fff;
        color: #24A1F5;
        border-radius: 5px;
        border:1px solid #24A1F5;
        margin: 20px auto 0;
    }
   .add_product .update_img .info_txt{
       text-align: center;
        font-size: 12px;
        color: #999;
        width: 88%;
        margin: auto;
        line-height: 46px;
        
   }
</style>

<template>
    <div class="add_product" style="padding-bottom: 20px;"> 
        <div class="reply" ><img src="static/wenhao.png">&nbsp;有任何疑问请戳这里&nbsp;<img src="static/hand.png"></div>
        <hr>
        <form :model='fm_data'>
            <van-cell-group>
                <van-field
                    v-model="fm_data.name"
                    label="产品名称"
                    placeholder="请输入您的产品名称"
                />

                <van-field
                    v-model="fm_data.desp"
                    type="textarea"
                    label="产品用途"
                    placeholder="如：本外观设计产品用于室外照明"
                />
                <van-field
                    v-model="fm_data.key_points"
                    label="设计要点"
                    placeholder="如：照明"
                />
            </van-cell-group>
        <hr>
        
        <div class="update_img">
      
            <h2 style="text-align:center;font-size:22px;margin-top: 15px;">单一产品</h2>
            <p class="info_txt" style="border-bottom: 1px solid #ccc;">（如需发布套装产品，请登陆PC端）</p>
            <van-uploader :after-read="ios_more_upload" multiple="multiple" v-if="Model_type=='ios'">
                <button class="upload_btn" style="margin:20px auto 10px;" >上传图片</button>
            </van-uploader>
            <button class="upload_btn" style="margin:20px auto 10px;" @click.prevent="android_more_upload" v-if="Model_type=='android'">上传图片</button>
            <p class="info_txt">（如需发布套装产品，请登陆PC端）</p>
            <div class="pic_box" >
                <div class="case_pic" v-for=" (v,i) in pic_names" :key="i" @click="pic_index=i" >
                    <van-uploader :after-read="onUpload_case" >
                        <img :src="images[i].url?images[i].url:'static/case_'+v+'.jpg'" >
                    </van-uploader>
                    <p @click="show_name_list=true"><span>{{images[i].pic_name}}</span>  <van-icon name="edit" style="font-size:20px;float:right" /></p>
                </div>
            </div>
            <div class="bottom">
                <div class="switch"><p>色彩保护 </p><p>包含产品的色彩</p><van-switch v-model="fm_data.is_color_protection" size="25px" style="margin-top:3px"/><div class="clear"></div></div> 
                <hr>
                <van-field
                    v-model="fm_data.other"
                    label="其他情况说明"
                    type="textarea"
                    placeholder="如有其他内容需要补充说明，请在此处填写"
                    class="explain"
                    rows="3"
                    border
                    :autosize="{maxHeight: 100, minHeight: 50}"
                />
            </div>
            <button class="fm_btn" :disabled="chenk_empty" @click.prevent="handleSubmit" >下一步</button>
      
        </div>
            
        </form>
        <van-popup v-model="show_name_list" position="bottom" >
            <van-picker show-toolbar @cancel="show_name_list=false" @confirm="onConfirm" :columns="pic_names" />
        </van-popup>
    </div>
</template>
<script>
import wx from "weixin-js-sdk"
import { Field,Tab,Uploader,Switch,Popup,Picker  } from 'vant';
import {pubUpdate,jssdk} from '@/assets/api'
import  {mapMutations,mapState } from 'vuex';
import lrz from 'lrz'  

export default {
    data(){
        return {
            Model_type:'',
            show_name_list:false,
            images:[],
            pic_index:0,
            pic_names:["主视图","后视图","俯视图","仰视图","左视图","右视图","立体图"],
            fm_data:{
                suit:[],
                attachment:[],
                other:'',
                name:'',
                desp:'',
                key_points:'',
                is_color_protection:false,
            },
         }
    },
    components:{
        'van-field':Field,
        "van-uploader":Uploader,
        'van-switch':Switch,
        "van-popup":Popup,
        "van-picker":Picker
    },
    filters:{
        str_china:function(val){
            let strIns = '', chnStr = '';
            let unitPos = 0;
            let zero = true;
            let chnNumChar = ['零","一","二","三","四","五","六","七","八","九'];
            let chnUnitSection = ['","万","亿","万亿","亿亿'];
            let chnUnitChar = ['","十","百","千'];
            while(val > 0){
                var v = val % 10;
                if(v === 0){
                    if(!zero){
                        zero = true;
                        chnStr = chnNumChar[v] + chnStr;
                    }
                }else{
                    zero = false;
                    strIns = chnNumChar[v];
                    strIns += chnUnitChar[unitPos];
                    chnStr = strIns + chnStr;
                }
                unitPos++;
                val = Math.floor(val / 10);
            }
            return chnStr;
        }
        
    },
    methods:{
        ...mapMutations(['set_var']),
        ios_more_upload(file_list){
            if(!Array.isArray(file_list))
                file_list=[file_list]
            file_list.map((el,i)=>{
                lrz(el.file, {width:1920,quality:.7})  
                .then(res=>{
                    if(res.fileLen>2048000){
                        this.$toast.fail('请上传小于2M的图片');
                        return false
                    }
                    this.images.some((img_el,img_index)=>{
                        if(!img_el.url){
                            this.$set(this.images[img_index],'url',res.base64)
                            this.images[img_index].formData=res.formData
                            this.images[img_index].type='native'
                            return true
                        }
                    })
                    
                })
            })
        },
        oversize(){
            this.$toast.fail('上传失败，图片过大，最大允许2M');
        },
        onConfirm(val){
            this.show_name_list=false
            let tmp_name=this.images[this.pic_index].pic_name
            let index=this.images.findIndex(el=>el.pic_name==val)
            this.$set(this.images[index],'pic_name',tmp_name)
            this.$set(this.images[this.pic_index],'pic_name',val)
        },
        async handleSubmit(){
            let suit={}
            let attachment=[]
            const num=this.images.filter(el=>el.url).length
            let up_index=0
            if(!num) return

            for (const el of this.images) {
                if(!el.id&&el.type=='native'){
                      this.$toast.loading({
                        mask: true,
                        message: '正在上传第'+(++up_index)+'张',
                        duration:0,
                    });
                    const res= await pubUpdate(el.formData)
                    el.url=this.host+res.data.data.path
                    delete el.formData
                    el.id=res.data.data.id
                    
                }else if(!el.id&&el.type=='wx'){
                    this.$toast.loading({
                        mask: true,
                        message: '正在上传第'+(++up_index)+'张',
                        duration:0,
                    });
                    // const res=await wx.uploadImage({
                    //     localId:el, // 图片的localID
                    //     isShowProgressTips: 1, // 默认为1，显示进度提示
                    // });
                    // console.log(res);
                    wx.uploadImage({
                        localId:el, // 图片的localID
                        isShowProgressTips: 1, // 默认为1，显示进度提示
                        success:res=>{
                            console.log(res);
                            
                        }
                    })
                   

                    // el.url=this.host+res.data.data.path
                    // el.id=res.data.data.id
                }
                if(el.id){
                    suit[el.pic_name]=el.id
                    attachment.push({ case_id:0,case_no:0,attachment_id:el.id,"type":"外观专利图" })
                    if(attachment.length==num){
                        this.$toast.clear()
                        const fm=Object.assign(JSON.parse(JSON.stringify(this.fm_data)),{
                            suit:{'整体':[suit]},attachment
                        })
                        this.set_var({var_name:'fm',set_type:'obj',data:fm})
                        this.$router.push({  name:'list_person'});
                        return
                    }
                }
            }
        },
        onUpload_case(data){  //单个上传
            lrz(data.file, {width:1920,quality:.7})  
            .then(res=>{
                 if(res.fileLen>2048000){
                    this.$toast.fail('请上传小于2M的图片');
                    return false
                }
                this.$set(this.images[this.pic_index],'url',res.base64)
                this.images[this.pic_index].type='native'
                this.images[this.pic_index].formData=res.formData

            })
        },
        android_more_upload(){
            wx.chooseImage({
                count: 7-this.images.filter(el=>el.url).length, 
                sizeType: ['compressed'], 
                sourceType: ['album', 'camera'], 
                success: res=>{
                    res.localIds.forEach(el=>{
                        for (let index = 0; index < 7; index++) {
                            if(!this.images[index].url){
                                this.$set(this.images[index],'url',el)
                                this.images[index].type='wx'
                                return
                            }
                        }
                       
                    })
                }
                
            });

        }
    },
    computed:{
        ...mapState(['fm']),
        chenk_empty:function(){
            return false

            // if(!this.fm_data.name || !this.fm_data.desp  || !this.fm_data.key_points )
            //     return true
            // else
            //     return this.active?!Object.keys( this.fm_data.Whole).length:!Object.keys( this.fm_data.alonePics).length
        }
    },
    created(){
        this.images=this.pic_names.map(el=>{
            return {pic_name:el}
        })
        let fm=localStorage.getItem('fm')
        if(fm){
            fm=JSON.parse(fm)
            this.fm_data=fm
        }
        let images=localStorage.getItem('images')
        if(images){
            images=JSON.parse(images)
            this.images=images
        }
        const u = navigator.userAgent, app = navigator.appVersion;
        if(!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/))
            this.Model_type='ios'
        else if(u.indexOf('Android') > -1 || u.indexOf('Linux') > -1)
            this.Model_type='android'
        jssdk({list:'chooseImage,uploadImage,getLocalImgData',url:window.location.href})
        .then(res=>{
            if(res){
                let config={}
                config.debug=false
                config.appId=res.data.data.config.appId
                config.nonceStr=res.data.data.config.nonceStr
                config.signature=res.data.data.config.signature
                config.timestamp=res.data.data.config.timestamp
                config.jsApiList=['chooseImage','uploadImage','getLocalImgData']
                wx.config(config)
                wx.error(res=>{
                    this.$toast.fail('微信参数异常');
                });  
            }
        })
    },
    beforeRouteLeave(to, from, next){
        localStorage.setItem('fm',JSON.stringify(this.fm_data))
        this.fm_data.is_color_protection=Boolean(this.fm_data.is_color_protection)
        localStorage.setItem('images',JSON.stringify(this.images))
        next()
    }

}
</script>
